/*
This file is part of La Linea.

La Linea is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

La Linea is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with La Linea.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Curve.h"

Curve::Curve(void)
{
	_origins[0] = 0;
	_origins[1] = 0;
	_controlpoint = 0;
}


Curve::~Curve(void)
{
	if(_origins[0])
		delete _origins[0];
	if(_controlpoint)
		delete _controlpoint;
}

Curve* Curve::copy(){
	Curve* newCurve = new Curve();
	if(!_origins[0] || !_origins[1] || !_controlpoint) return newCurve;
	
	newCurve->_origins[0] = _origins[0]->copy();
	newCurve->_origins[1] = _origins[1]->copy();
	newCurve->_controlpoint = _controlpoint->copy();
	
	return newCurve;
}

// Based on http://segfaultlabs.com/docs/quadratic-bezier-curve-length
float Curve::getLength(void)
{
	if(!_origins[0] || !_origins[1] || !_controlpoint) return -1.f;

	Vector2f a, b;

	a.x = _origins[0]->_pos.x - 2*_controlpoint->_pos.x + _origins[1]->_pos.x;
	a.y = _origins[0]->_pos.y - 2*_controlpoint->_pos.y + _origins[1]->_pos.y;

	b.x = 2*_controlpoint->_pos.x - 2*_origins[0]->_pos.x;
	b.y = 2*_controlpoint->_pos.y - 2*_origins[0]->_pos.y;

	float A = 4*(a.x*a.x + a.y*a.y);
	float B = 4*(a.x*b.x + a.y*b.y);
	float C = b.x*b.x + b.y*b.y;

	float Sabc = 2*sqrt(A+B+C);
	float A_2 = sqrt(A);
	float A_32 = 2*A*A_2;
	float C_2 = 2*sqrt(C);
	float BA = B/A_2;

	return ( A_32*Sabc + A_2*B*(Sabc-C_2) + (4*C*A-B*B)*log( (2*A_2+BA+Sabc)/(BA+C_2) ) )/(4*A_32);
}
